package tenglang.resource.service;

import auth.server.inter.AuthConstants;
import auth.server.inter.security.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import tenglang.common.constant.Constants;
import tenglang.common.jackson.BeanUtils;
import tenglang.common.redis.RedisCache;
import tenglang.common.utils.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 * 
 * @author ruoyi
 */
@Component
public class TokenService
{
    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ResourceServerTokenServices resourceServerTokenServices;



    /**
     * 获取用户身份信息
     * 
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = getToken(request);
        if(StringUtils.isNotBlank(token)){
            OAuth2Authentication oAuth2Authentication=resourceServerTokenServices.loadAuthentication(token);
            Object  principal=oAuth2Authentication.getPrincipal();
            auth.server.inter.security.LoginUser loginUser=redisCache.getCacheObject(AuthConstants.LOGIN_TOKEN_KEY+(String)principal);
            Assert.notNull(loginUser,"用户已强制退出，请重新登录!");
            LoginUser loginUser1= null;
            try {
                loginUser1 = BeanUtils.getObjectMapper().readValue(loginUser.getUserDetail(), LoginUser.class);
            } catch (IOException e) {
                return null;
            }
            return loginUser1;
        }else{
             return null;
        }
    }



    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser()
    {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes)requestAttributes).getResponse();

        // 获取请求携带的令牌
        String token = getToken(request);
        if(StringUtils.isNotBlank(token)){
            OAuth2Authentication oAuth2Authentication=resourceServerTokenServices.loadAuthentication(token);
            Object  principal=oAuth2Authentication.getPrincipal();
            auth.server.inter.security.LoginUser loginUser=redisCache.getCacheObject(AuthConstants.LOGIN_TOKEN_KEY+(String)principal);
            Assert.notNull(loginUser,"用户已强制退出，请重新登录!");
            LoginUser loginUser1= null;
            try {
                loginUser1 = BeanUtils.getObjectMapper().readValue(loginUser.getUserDetail(), LoginUser.class);
            } catch (IOException e) {
                return null;
            }
            return loginUser1;
        }else{
            return null;
        }
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser)
    {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken()))
        {
            String userKey = getTokenKey(loginUser.getToken());
            redisCache.setCacheObject(userKey, loginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token)
    {
        if (StringUtils.isNotEmpty(token))
        {
            String userKey = getTokenKey(token);
            redisCache.deleteObject(userKey);
        }
    }


    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     * 
     * @param token 令牌
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser)
    {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        {
            String token = loginUser.getToken();
            loginUser.setToken(token);
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     * 
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser)
    {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }
    

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
        {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private String getTokenKey(String uuid)
    {
        return Constants.LOGIN_TOKEN_KEY + uuid;
    }
}
